<?php
/**
 * Created by PhpStorm.
 * User: CY
 * Date: 2018/3/27
 * Time: 15:25
 */

namespace app\api\service;


use think\Exception;

class WxMessage
{
    //
    private $sendUrl = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s';
    private $touser; // 接收者（用户）的 openid
    // 不让子类控制颜色
    private $color = 'black'; // 模板内容字体的颜色，不填默认黑色

    protected $tplID; // 微信模板消息id
    protected $page; // 用户点击模板后跳转的页面
    protected $formID; // 表单提交场景下，为 submit 事件带上的 formId；支付场景下，为本次支付的 prepay_id
    protected $data; // 模板内容，不填则下发空模板
    protected $emphasisKeyWord; // 模板需要放大的关键词，不填则默认无放大

    /**
     * 构造方法中获得AccessToken并组合模板发送链接
     * WxMessage constructor.
     */
    function __construct() {
        $accessToken = new AccessToken();
        $token = $accessToken->get();
        $this->sendUrl = sprintf($this->sendUrl,$token);
    }

    /**
     * 发送模板消息
     * @param $openID
     * @return bool
     * @throws Exception
     */
    protected function sendMessage($openID){
        $data = [
            'touser' => $openID,
            'template_id' => $this->tplID,
            'page' => $this->page,
            'form_id' => $this->formID,
            'data' => $this->data,
            'color' => $this->color,
            'emphasis_keyword' => $this->emphasisKeyWord
        ];

        $result = curl_post($this->sendUrl,$data);
        $result = json_decode($result,true);
        if($result['errcode'] == 0){
            return true;
        }else{
            throw new Exception('模板消息发送失败，' . $result['errmsg']);
        }
    }

}